import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import useStore from '@/store';

export const Layout = () => import('@/layout/index.vue');

// 参数说明: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
// 静态路由
export const constantRoutes: Array<RouteRecordRaw> = [
  {
    path: '/redirect',
    component: Layout,
    meta: { hidden: true },
    children: [
      {
        path: '/redirect/:path(.*)',
        component: () => import('@/views/redirect/index.vue')
      }
    ]
  },
  {
    path: '/404',
    component: () => import('@/views/error-page/404.vue'),
    meta: { hidden: true }
  },

  {
    path: '/',
    component: Layout,
    meta: { hidden: true },
    redirect: 'shop',
    children: []
  },
  // 多级嵌套路由
  {
    path: '/shop',
    component: Layout,
    redirect: '/shop/product/list',
    name: 'Shop',
    meta: { title: '商品管理', icon: 'nested' },
    children: [
      {
        path: 'product',
        component: () => import('@/views/shop/product/index.vue'),
        name: 'Product',
        meta: { title: '商品管理' },
        redirect: '/shop/product/list',
        children: [
          {
            path: 'list',
            component: () => import('@/views/shop/product/list.vue'),
            name: 'List',
            meta: { title: '商品列表' },
          },
          {
            path: 'detail',
            component: () => import('@/views/shop/product/detail.vue'),
            name: 'Detail',
            meta: { title: '商品详情', hidden: true },
          }
        ]
      },
    ]
  }
];

// 创建路由
const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRoutes as RouteRecordRaw[],
  // 刷新时，滚动条位置还原
  scrollBehavior: () => ({ left: 0, top: 0 })
});

// 重置路由
export function resetRouter() {
  const { permission } = useStore();
  permission.routes.forEach(route => {
    const name = route.name;
    if (name && router.hasRoute(name)) {
      router.removeRoute(name);
    }
  });
}

export default router;
